<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      height="550"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板中文名称" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tpl_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板类型" width="150" align="center">
        <template slot-scope="{row}">
          <span>{{ tplTypeName[row.tpl_type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板标签" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tpl_label }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板签名" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tpl_sign }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板CODE" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tpl_code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板参数" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tpl_param }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板内容" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tpl_content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="模板说明" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.tpl_remark }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" min-width="200" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.cate_status==0"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex flex-center">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog class="data-form-dialog" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 450px;">
        <el-form-item label="模板类型">
          <el-select v-model="temp.tpl_type" class="filter-item" placeholder="Please select">
            <el-option v-for="(item, key) in typeOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="模板中文名"
          prop="tpl_name"
          :rules="[
            { required: true, message: '请填写模板中文名'}
          ]"
        >
          <el-input v-model="temp.tpl_name" />
          <span class="input-tip-text">标识模板用</span>
        </el-form-item>

        <el-form-item
          label="模板标签"
          prop="tpl_label"
          :rules="[
            { required: true, message: '请填写模板标签'},
            { type: 'string', message: '模板标签必需是字符串'},
            { min: 2, max: 30, message: '长度2-30'}
          ]"
        >
          <el-input v-model="temp.tpl_label" />
          <span class="input-tip-text">如登录验证码：login</span>
        </el-form-item>

        <el-form-item
          label="模板签名"
          prop="tpl_sign"
          :rules="[
            { required: true, message: '请填写模板签名'}
          ]"
        >
          <el-input v-model="temp.tpl_sign" />
          <span class="input-tip-text">具体请查看短信平台</span>
        </el-form-item>

        <el-form-item
          label="模板CODE"
          prop="tpl_code"
          :rules="[
            { required: true, message: '请填写模板CODE'}
          ]"
        >
          <el-input v-model="temp.tpl_code" />
          <span class="input-tip-text">具体请查看短信平台</span>
        </el-form-item>

        <el-form-item
          label="模板参数"
          prop="tpl_param"
          :rules="[
            { required: true, message: '请填写模板参数'}
          ]"
        >
          <el-input v-model="temp.tpl_param" />
          <span class="input-tip-text">模板中参数对照传参，json格式, 如模板有参数`${code}`：{"code": "captcha"}</span>
        </el-form-item>

        <el-form-item
          label="模板内容"
          prop="tpl_content"
          :rules="[
            { required: true, message: '请填写模板内容'}
          ]"
        >
          <el-input v-model="temp.tpl_content" />
          <span class="input-tip-text">具体请查看短信平台</span>
        </el-form-item>

        <el-form-item
          label="模板备注"
          prop="tpl_remark"
          :rules="[
            { required: true, message: '请填写模板备注'}
          ]"
        >
          <el-input v-model="temp.tpl_remark" />
          <span class="input-tip-text">模板备注</span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :loading="submitLoading" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchSmsList, fetchUpdateSms, fetchCreateSms, fetchDeleteSms } from '@/api/sms'
import Pagination from '@/components/Pagination'

export default {
  name: 'Sms',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      submitLoading: false, // 提交中
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      tplTypeName: { aliyun: '阿里云' },
      typeOptions: [{ name: '阿里云', id: 'aliyun' }],
      listQuery: {
        sort: '-id'
      },
      temp: {
        id: 0,
        tpl_type: 'aliyun',
        tpl_name: '',
        tpl_sign: '',
        tpl_code: '',
        tpl_param: '',
        tpl_content: '',
        tpl_remark: ''
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchSmsList(this.listQuery).then(response => {
        this.list = response.data
        this.listLoading = false
      }, () => {
        this.listLoading = false
      })
    },
    getImage(url) {
      return this.$utils.getImage(url)
    },
    getStatusString(status) {
      return this.statusOptions[status]
    },
    getStatusType(status) {
      return this.statusType[status]
    },
    // 清空表单
    resetTemp() {
      this.changeCateIcon = false
      this.temp = {
        id: 0,
        tpl_type: 'aliyun',
        tpl_name: '',
        tpl_sign: '',
        tpl_code: '',
        tpl_param: '',
        tpl_content: '',
        tpl_remark: ''
      }
    },
    // 创建
    handleCreate() {
      if (this.dialogStatus === 'update') {
        this.resetTemp()
      }
      this.temp.id = 0
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 编辑
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 排序更新
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.getList()
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      if (sort === `+${key}`) {
        return 'ascending'
      } else if (sort === `-${key}`) {
        return 'descending'
      }
    },
    parseTimes(time, cFormat) {
      return this.$utils.parseTime(time, cFormat)
    },
    // 提交表单
    createData() {
      this.submitLoading = true
      this.submitData()
    },
    updateData() {
      this.submitLoading = true
      this.submintUpdateData()
    },
    submintUpdateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchUpdateSms(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.submitLoading = false
          }, () => {
            this.submitLoading = false
          })
        } else {
          this.submitLoading = false
        }
      })
    },
    submitData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          fetchCreateSms(this.temp).then((res) => {
            this.temp.id = res.data.id
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.resetTemp()
            this.$notify({
              title: 'Success',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })

            this.submitLoading = false
          }, (err) => {
            console.log(err)
            this.submitLoading = false
          })
        } else {
          this.submitLoading = false
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '执行中...'

            fetchDeleteSms(row.id).then((res) => {
              this.$notify({
                title: 'Success',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              this.list.splice(index, 1)

              instance.confirmButtonLoading = false
              done()
            }, (err) => {
              this.$notify({
                title: 'Success',
                message: err.message || '删除成功',
                type: 'error',
                duration: 2000
              })
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        }
      })
    }
  }
}
</script>

<style>
  .el-dialog {
    width: 550px;
  }

  .icon-uploader {
    border: 1px solid #eee;
    width: 2.5rem;
    height: 2.5rem;
    align-items: center;
    display: flex;
    justify-content: center;
    overflow: hidden;
    cursor: pointer;
  }
  .cate-icon {
    width: 2.5rem;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
